import time
from typing import Dict, Any, Optional
from tenacity import retry, stop_after_attempt, wait_exponential
from intelli_port.commons.audit import audit_event, write_ops_log
from intelli_port.commons.config import load_settings
import httpx
from intelli_port.data_layer.clients import mysql_execute_write

@retry(reraise=False, stop=stop_after_attempt(3), wait=wait_exponential(multiplier=0.2, min=0.2, max=2.0))
def checkin_ticket(payload: Dict[str, Any], idem_key: Optional[str] = None) -> Dict[str, Any]:
    ticket_no = payload.get("ticket_no")
    ok = False
    s = load_settings()
    if getattr(s, "checkin_base_url", ""):
        try:
            headers = {"Authorization": f"Bearer {s.external_auth_token}"} if getattr(s, "external_auth_token", "") else {}
            with httpx.Client(timeout=float(getattr(s, "external_timeout_s", 2.0))) as client:
                r = client.post(s.checkin_base_url.rstrip("/") + "/checkin", json={"ticket_no": ticket_no}, headers=headers)
                if r.status_code == 200:
                    data = r.json()
                    ok = bool(data.get("request_created", False))
        except Exception:
            ok = False
    else:
        try:
            if ticket_no:
                mysql_execute_write("INSERT INTO service_requests(passenger_id, service_type, priority, status, location, created_at) VALUES(NULL,%s,%s,%s,%s,NOW())", ("check_in", 5, "pending", None))
                ok = True
        except Exception:
            ok = False
    write_ops_log("INFO", "checkin.create", {"ticket_no": ticket_no, "ok": ok})
    audit_event("checkin", "service", "check_in", payload, result="success" if ok else "failed")
    return {"accepted": True, "request_created": ok}